<?php

namespace MLM\Controller;

use Zend\View\Model\ViewModel;
use Zend\Authentication\Result;
use Zend\Authentication\AuthenticationService;
use Zend\Authentication\Adapter\DbTable as AuthAdapter;

class TransactionController extends \MLM\Model\Generic\Controller {

    
    public function indexAction() {
        $identity = $this->hasSession();
        $this->layout('layout/member');
        return new ViewModel();
    }

    public function poinAction() {
        $identity = $this->hasSession();

       // $storage = new \MLM\Model\Transaction\Storage($this->_db);
       // $member = new \MLM\Model\Transaction($storage);

        $memberId = $identity->member_id;

        $accStorage = new \MLM\Model\Member\Account\Storage($this->_db);
        $getAccount = $accStorage->getAccountDetail($memberId);

        $dataAccount = array();
        while ($getAccount->next()) {
                $account = $getAccount->current();
                $dataAccount['account_num'] = $account['account_num'];
                $dataAccount['account_name'] = $account['account_name'];
        }

        $dataSaldo = $accStorage->getTotalSaldoByPeriod($memberId, $dataAccount['account_num'], "", $dateTmp1, $dateTmp2);

        //print_r($transType); die();

        //Get Messages Notif
        $this->getMsgNotif($memberId);


        $view = new ViewModel();
        $view->setVariable('dataAccount', $dataAccount);
        $view->setVariable('dataSaldo', $dataSaldo);

        $this->layout('layout/member');

        //Get Messages Notif
        $this->getMsgNotif($identity->member_type_id, $memberId);

        return $view;
    }


    public function trackingAction()
    {

        $identity = $this->hasSession();
        $this->layout('layout/member');

        $date1 = date('Ymd', mktime(0, 0, 0, date("m"), date("d") - 7, date("Y")));
        $date2 = date('Ymd');

        $dateTmp1 = date('Y-m-d', mktime(0, 0, 0, date("m"), date("d") - 7, date("Y")));
        $dateTmp2 = date('Y-m-d');
        
        $memberId = $identity->member_id;

        $accStorage = new \MLM\Model\Member\Account\Storage($this->_db);
        $getAccount = $accStorage->getAccountDetail($memberId);

        $dataAccount = array();
        while ($getAccount->next()) {
                $account = $getAccount->current();
                $dataAccount['account_num'] = $account['account_num'];
                $dataAccount['account_name'] = $account['account_name'];
        }

        $dataSaldo = $accStorage->getTotalSaldoByPeriod($memberId, $dataAccount['account_num'], "", $date1, $date2);

        $transStorage = new \MLM\Model\Transaction\Storage($this->_db);
        $transType = $transStorage->getTransType();

        //print_r($transType); die();

        //Get Messages Notif
        $this->getMsgNotif($identity->member_type_id, $memberId);


        $view = new ViewModel();

        $script = $this->getServiceLocator()->get('viewhelpermanager')
                ->get('inlineScript');
        $script->appendScript("
          jQuery(function($) {
            $('.chosen-select').chosen();

            $('#modal-form').on('shown.bs.modal', function() {
                $(this).find('.chosen-container').each(function() {
                    $(this).find('a:first-child').css('width', '210px');
                    $(this).find('.chosen-drop').css('width', '210px');
                    $(this).find('.chosen-search input').css('width', '200px');
                });
            })
        })
        ");
        
        $view->setVariable('transType', $transType);
        $view->setVariable('dateTmp1', $dateTmp1);
        $view->setVariable('dateTmp2', $dateTmp2);
        $view->setVariable('dataAccount', $dataAccount);
        $view->setVariable('dataSaldo', $dataSaldo);
        //$view->setTerminal(true);
        return $view;

    }


    public function bonuslistAction()
    {

        $identity = $this->hasSession();
        $this->layout('layout/member');

        $date1 = date('Ymd', mktime(0, 0, 0, date("m"), date("d") - 7, date("Y")));
        $date2 = date('Ymd');

        $dateTmp1 = date('Y-m-d', mktime(0, 0, 0, date("m"), date("d") - 7, date("Y")));
        $dateTmp2 = date('Y-m-d');

        $memberId = $identity->member_id;

        $accStorage = new \MLM\Model\Member\Account\Storage($this->_db);
        $getAccount = $accStorage->getAccountDetail($memberId);

        $dataAccount = array();
        while ($getAccount->next()) {
                $account = $getAccount->current();
                $dataAccount['account_num'] = $account['account_num'];
                $dataAccount['account_name'] = $account['account_name'];
        }

        $dataSaldo = $accStorage->getTotalSaldoByPeriod($memberId, $dataAccount['account_num'], "", $date1, $date2);

        $transStorage = new \MLM\Model\Transaction\Storage($this->_db);
        $transType = $transStorage->getTransType("Q");

        //print_r($transType); die();

        //Get Messages Notif
        $this->getMsgNotif($identity->member_type_id, $memberId);


        $view = new ViewModel();

        $script = $this->getServiceLocator()->get('viewhelpermanager')
                ->get('inlineScript');
        $script->appendScript("
          jQuery(function($) {
            $('.chosen-select').chosen();

            $('#modal-form').on('shown.bs.modal', function() {
                $(this).find('.chosen-container').each(function() {
                    $(this).find('a:first-child').css('width', '210px');
                    $(this).find('.chosen-drop').css('width', '210px');
                    $(this).find('.chosen-search input').css('width', '200px');
                });
            })
        })
        ");

        $view->setVariable('transType', $transType);
        $view->setVariable('dateTmp1', $dateTmp1);
        $view->setVariable('dateTmp2', $dateTmp2);
        $view->setVariable('dataAccount', $dataAccount);
        $view->setVariable('dataSaldo', $dataSaldo);
        //$view->setTerminal(true);
        return $view;

    }

    
    public function totalsaldoAction(){
        $getParams = $this->getRequest()->getQuery();

        $transType = (isset($getParams['transType'])) ? $getParams['transType'] : "";
        $accNum = (isset($getParams['accNum'])) ? $getParams['accNum'] : "";
        $mutation = (isset($getParams['mutation'])) ? $getParams['mutation'] : "";
        $date1 = (isset($getParams['date1'])) ? str_replace('-', '', $getParams['date1']) : date('Ymd', mktime(0, 0, 0, date("m")  , date("d")-7, date("Y")));
        $date2 = (isset($getParams['date2'])) ? str_replace('-', '', $getParams['date2']) : date('Ymd');

        $accStorage = new \MLM\Model\Member\Account\Storage($this->_db);
        
        $dataSaldo = $accStorage->getTotalSaldoByPeriod($memberId, $accNum, $transType, $date1, $date2);

        if ($mutation == ""){
            $tmp = '<table cellpadding="5px">
                        <tr>
                            <td>Total Kredit</td>
                            <td>: </td>
                            <td align="right"> '.$dataSaldo['kredit'] .'</td>
                        </tr>
                        <tr>
                            <td>Total Debet</td>
                            <td>: </td>
                            <td align="right"> '.$dataSaldo['debet'] .'</td>
                        </tr>
                        <tr>
                            <td>Saldo Akhir</td>
                            <td>: </td>
                            <td align="right"> '.$dataSaldo['saldo'] .'</td>
                        </tr>
                </table>';
        }else{

                $tmp = '<table cellpadding="5px">
                    <tr>
                        <td>Total Bonus</td>
                        <td>: </td>
                        <td align="right"> '.$dataSaldo['kredit'] .'</td>
                    </tr>
                    <tr>
                        <td>Saldo Akhir</td>
                        <td>: </td>
                        <td align="right"> '.$dataSaldo['saldo'] .'</td>
                    </tr>
            </table>';

        }
            
        $view = new ViewModel();
        $view->setTerminal(true);
        $view->setVariable('data', $tmp);
        return $view;
    }


    public function topupAction() {

        $identity = $this->hasSession();

        $this->layout('layout/member');
        $view = new ViewModel();


        $data = array();

        $request = $this->getRequest();

        $db = $this->_db;
        $conn = $db->getDriver()->getConnection();
        $transAccStorage = new \MLM\Model\Member\Account\Storage($db);

        if ($request->isPost()) {

            $formData = $request->getPost();

            //$bankAccNo = $formData['bank_account_no'];
            $bank = $formData['slBank'];
            $jmlTopUp = $formData['jmlTopUp'];
            $tglTransfer = $formData['tglTransfer'];
            $catatan = $formData["catatan"];

            
            $data = array_merge($data,  get_object_vars($formData));

            $errorMsg = "";
            $msg = "";
            
            if ($errorMsg == "") {

                $conn->beginTransaction();

                // Insert topup
                $transStorage = new \MLM\Model\Transaction\Storage($db);
                $dataW = $transStorage->topup($identity->member_id, $identity->member_code, $bank, $jmlTopUp, $tglTransfer, $catatan);
                while($dataW->next()){
                        $res = $dataW->current();
                        $msg = $res["out_msg"];
                        $code = $res['out_code'];
                }

                if ($code == '0') {
                    $conn->commit();
                    return $this->redirect()->toUrl('topup?msg='.$msg);

                } else {
                    $conn->rollback();
                    $view->setVariable('errmsg', $msg);
                }
            }else{

                $view->setVariable('errmsg', $errorMsg);
            }


            //$this->view->id = $msg;
        } 

        $getParams = $this->getRequest()->getQuery();
        $view->setVariable('msg', $getParams["msg"]);
        $view->setVariable('data', $data);

        $script = $this->getServiceLocator()->get('viewhelpermanager')
                ->get('inlineScript');
        $script->appendScript("
         jQuery(function($) {

            $('.chosen-select').chosen();

            $('#modal-form').on('shown.bs.modal', function() {
                $(this).find('.chosen-container').each(function() {
                    $(this).find('a:first-child').css('width', '210px');
                    $(this).find('.chosen-drop').css('width', '210px');
                    $(this).find('.chosen-search input').css('width', '200px');
                });
            })

            $('.date-picker').datepicker({autoclose:true}).next().on(ace.click_event, function(){
                            $(this).prev().focus();
                    });
        })
        ");

        $script->appendScript('
          jQuery(function($) {
            $("textarea[class*=autosize]").autosize({append: "\n"});
        })
        ');

        //Get Messages Notif
        $this->getMsgNotif($identity->member_type_id, $identity->member_id);

        return $view;
    }


    public function transferAction() {

        $identity = $this->hasSession();

        $this->layout('layout/member');
        $view = new ViewModel();
        // init data and instance object

        $request = $this->getRequest();

        $db = $this->_db;
        $conn = $db->getDriver()->getConnection();
        $transAccStorage = new \MLM\Model\Member\Account\Storage($db);

        if ($request->isPost()) {

            $formData = $request->getPost();

            $fromAccount = $formData['acc_num'];
            $transfer = $formData['transfer'];
            $toAccount = $formData['to_account'];
            $minSaldo = $formData["min_saldo"];
            $notes = $formData["notes"];

            $data = get_object_vars($formData);
            
            $errorMsg = "";

            //Pastikan Balance
            //$modelRek = new Application_Model_Rekening();


            $getBalance = $transAccStorage->getTotalBalance($fromAccount);

            $balance = 0;
            while($getBalance->next()){
                $res = $getBalance->current();
                $balance = $res["amount"];
            }

            //cek minimum saldo
            if ($minSaldo > $balance || $minSaldo > ($balance - $transfer)) {
                $errorMsg .= "* Minimum Saldo tidak mencukupi.<br>";
            }


            /*
             * Cek Penarikan
             */

            if ($transfer > $balance) {
                $errorMsg .= "* Jumlah transfer lebih besar daripada jumlah saldo.<br>";

            }


            /*
             * Cek Akun Tujuan
             */            
            $toAcc = $transAccStorage->getAccountDetailByAcc($toAccount);
            $x = 0;
            while($toAcc->next()){
                    $res = $toAcc->current();
                    $x++;
            }
            if ($x == 0) {
                $errorMsg .= "* Nomor Akun Tujuan tidak terdaftar.<br>";

            }

            $msg = "";
            if ($errorMsg == "") {

                $conn->beginTransaction();

                // Insert Withdraw
                $transStorage = new \MLM\Model\Transaction\Storage($db);
                $dataW = $transStorage->transfer($identity->member_id, $fromAccount, $transfer, $toAccount, $notes);
                while($dataW->next()){
                        $res = $dataW->current();
                        $msg = $res["out_msg"];
                        $code = $res['out_code'];
                }

                if ($code == '0') {
                    $conn->commit();
                    return $this->redirect()->toUrl('transfer?msg='.$msg);

                } else {
                    $conn->rollback();
                    $view->setVariable('errmsg', $msg);
                }
            }else{

                $view->setVariable('errmsg', $errorMsg);
                $view->setVariable('data', $data);
            }


            //$this->view->id = $msg;
        } else {

            $account = $identity->member_code;

            $getBalance = $transAccStorage->getTotalBalance($account);
            while($getBalance->next()){
                    $balance = $getBalance->current();
                    $view->setVariable('amount', $balance["amount"]);
                    $view->setVariable('amount2', $balance["amount2"]);
            }
            

            $view->setVariable('acc_num', $account);

            //Get Minimal Balance
            $configStorage = new \MLM\Model\Sysconfig\Storage($db);
            $getMinBalance = $configStorage->getConfigByName('MIN_BALANCE');
            while($getMinBalance->next()){
                    $minBalance = $getMinBalance->current();
                    $view->setVariable('minbalance', $minBalance['int_value']);
            }


        }

        $getParams = $this->getRequest()->getQuery();
        $view->setVariable('msg', $getParams["msg"]);

        //Get Messages Notif
        $this->getMsgNotif($identity->member_type_id, $identity->member_id);

        return $view;
    }

    
    public function withdrawAction() {
        
        $identity = $this->hasSession();

        $this->layout('layout/member');
        $view = new ViewModel();
        // init data and instance object   

        $request = $this->getRequest();

        $db = $this->_db;
        $conn = $db->getDriver()->getConnection();
        $transAccStorage = new \MLM\Model\Member\Account\Storage($db);

        if ($request->isPost()) {            

            $formData = $request->getPost();

            $fromAccount = $formData['acc_num'];
            $tarik = $formData['tarik'];
            $bank = $formData['bank_name'];
            $minSaldo = $formData["min_saldo"];
            $biaya = $formData["biaya"];;


            $errorMsg = "";

            //Pastikan Balance
            //$modelRek = new Application_Model_Rekening();
            

            $getBalance = $transAccStorage->getTotalBalance($fromAccount);
            
            $balance = 0;
            while($getBalance->next()){
                $res = $getBalance->current();
                $balance = $res["amount"];
            }

            //cek minimum saldo
            if ($minSaldo > $balance || $minSaldo > ($balance - ($tarik + $biaya))) {
                $errorMsg .= "* Minimum Saldo tidak mencukupi.<br>";
            }


            /*
             * Cek Penarikan
             */

            if (($tarik + $biaya) > $balance) {
                $errorMsg .= "* Penarikan + Biaya lebih besar daripada jumlah saldo.<br>";

            }

 
            
            $msg = "";
            if ($errorMsg == "") {

                $conn->beginTransaction();

                // Insert Withdraw
                $transStorage = new \MLM\Model\Transaction\Storage($db);
                $dataW = $transStorage->withdraw($identity->member_id, $fromAccount, $tarik, $bank);
                while($dataW->next()){
                        $res = $dataW->current();
                        $msg = $res["out_msg"];
                        $code = $res['out_code'];
                }

                if ($code == '0') {
                    $conn->commit();
                    return $this->redirect()->toUrl('withdraw?msg='.$msg);
                    
                } else {
                    $conn->rollback();
                    $view->setVariable('errmsg', $msg);
                }
            }else{

                $view->setVariable('errmsg', $errorMsg);
            }


            //$this->view->id = $msg;
        } else {

            $account = $identity->member_code;

            $getBalance = $transAccStorage->getTotalBalance($account);
            while($getBalance->next()){
                    $balance = $getBalance->current();
                    $view->setVariable('amount', $balance["amount"]);
                    $view->setVariable('amount2', $balance["amount2"]);
            }

            $getBank = $transAccStorage->getMemberAccountBank($identity->member_id);
            while($getBank->next()){
                    $bank = $getBank->current();
                    $view->setVariable('bank', $bank['bank_acc_num']);
            }

            $view->setVariable('acc_num', $account);


            //Get withdrawal Fee
            $configStorage = new \MLM\Model\Sysconfig\Storage($db);
            $getFee = $configStorage->getConfigByName('CHARGE_WITHDRAW');
            while($getFee->next()){
                    $fee = $getFee->current();
                    $view->setVariable('biaya', $fee['int_value']);
            }

            //Get Minimal Balance
            $configStorage = new \MLM\Model\Sysconfig\Storage($db);
            $getMinBalance = $configStorage->getConfigByName('MIN_BALANCE');
            while($getMinBalance->next()){
                    $minBalance = $getMinBalance->current();
                    $view->setVariable('minbalance', $minBalance['int_value']);
            }


            //Get Minimal WIthdraw
            $getMinWithdraw = $configStorage->getConfigByName('MIN_WITHDRAW');
            while($getMinWithdraw->next()){
                    $minWithdraw = $getMinWithdraw->current();
                    $view->setVariable('minwithdraw', $minWithdraw['int_value']);
            }

        }

        $getParams = $this->getRequest()->getQuery();
        $view->setVariable('msg', $getParams["msg"]);

        //Get Messages Notif
        $this->getMsgNotif($identity->member_type_id, $identity->member_id);
        
        return $view;
    }


    public function payAction() {
        $identity = $this->hasSession();

       // $storage = new \MLM\Model\Transaction\Storage($this->_db);
       // $member = new \MLM\Model\Transaction($storage);

        $memberId = $identity->member_id;
        //$profile= $storage->getMemberDetail($memberId);

        $view = new ViewModel();
        //$view->setVariable('memberProfile', $profile);
        $this->layout('layout/member');

        //Get Messages Notif
        $this->getMsgNotif($identity->member_type_id, $memberId);
        
        return $view;
    }


    public function buyAction() {
        $identity = $this->hasSession();

       // $storage = new \MLM\Model\Transaction\Storage($this->_db);
       // $member = new \MLM\Model\Transaction($storage);

        $memberId = $identity->member_id;
        //$profile= $storage->getMemberDetail($memberId);

        $view = new ViewModel();
        //$view->setVariable('memberProfile', $profile);
        $this->layout('layout/member');

        //Get Messages Notif
        $this->getMsgNotif($identity->member_type_id, $memberId);
        
        return $view;
    }


    public function rewardlistAction()
    {

        $identity = $this->hasSession();
        $this->layout('layout/member');

        $memberId = $identity->member_id;

        $accStorage = new \MLM\Model\Member\Account\Storage($this->_db);
        $getAccount = $accStorage->getAccountDetail($memberId);

        $dataAccount = array();
        while ($getAccount->next()) {
                $account = $getAccount->current();
                $dataAccount['account_num'] = $account['account_num'];
                $dataAccount['account_name'] = $account['account_name'];
        }


        $memberStorage = new \MLM\Model\Member\Storage($this->_db);
        $getNumMitra = $memberStorage->getNumMitra($identity->member_id);
        $numMitra = 0;
        while($getNumMitra->next()){
                $res = $getNumMitra->current();
                $numMitra = $res['total'];
        }

        //Get Messages Notif
        $this->getMsgNotif($identity->member_type_id, $memberId);
        
        $view = new ViewModel();

   
        $view->setVariable('dataAccount', $dataAccount);
        $view->setVariable('numMitra', $numMitra);

        //$view->setTerminal(true);
        return $view;

    }


    public function claimrewardAction() {

        $identity = $this->hasSession();

        $this->layout('layout/member');
        $view = new ViewModel();
        // init data and instance object

        $request = $this->getRequest();

        $db = $this->_db;
        $conn = $db->getDriver()->getConnection();  

        if ($request->isPost()) {

            $formData = $request->getPost();
            $bonusRewardId = $formData['bonusRewardId'];
            $rewardId = $formData['rewardId'];
            
            $conn->beginTransaction();

            // Insert Withdraw
            $transStorage = new \MLM\Model\Transaction\Storage($db);
            $dataW = $transStorage->claimReward($identity->member_id, $identity->member_code, $bonusRewardId, $rewardId);
            while($dataW->next()){
                    $res = $dataW->current();
                    $msg = $res["out_msg"];
                    $code = $res['out_code'];
            }

            if ($code == '0') {
                $conn->commit();
                $view->setVariable('msg', $msg);
                

            } else {
                $conn->rollback();
                $view->setVariable('errmsg', $msg);
            }
            
        } 

        $getParams = $this->getRequest()->getQuery();        
        $view->setTerminal(true);
        return $view;
    }


    public function transferwalletAction() {

        $identity = $this->hasSession();

        $this->layout('layout/member');
        $view = new ViewModel();
        // init data and instance object

        $request = $this->getRequest();

        $db = $this->_db;
        $conn = $db->getDriver()->getConnection();
        $transAccStorage = new \MLM\Model\Member\Account\Storage($db);

        if ($request->isPost()) {

            $formData = $request->getPost();
            $fromAccount = $identity->member_code;
            $transfer = $formData['transfer'];
            $toAccount = $fromAccount;
            $minSaldo = $formData["minbalance"];
            $transType = $formData["transType"];


            $data = get_object_vars($formData);

            $errorMsg = "";

            //Pastikan Balance
            //$modelRek = new Application_Model_Rekening();


            $getBalance = $transAccStorage->getTotalBalance($fromAccount);

            $balance = 0;
            while($getBalance->next()){
                $res = $getBalance->current();
                
                $balanceEWallet = $res["amount"];
                $balanceRoiWallet = $res["amount_1"];
                $balanceRefWallet = $res["amount_2"];
                $balanceBinWallet = $res["amount_3"];
                $balanceShopWallet = $res["amount_4"];

                if ($transType == 'T008') $balance = $balanceRoiWallet;
                if ($transType == 'T009') $balance = $balanceRefWallet;
                if ($transType == 'T010') $balance = $balanceBinWallet;
                if ($transType == 'T011') $balance = $balanceShopWallet;
                
            }

            //cek minimum saldo
            if ($minSaldo > $balance || $minSaldo > ($balance - $transfer)) {
                $errorMsg .= "* Your Balance is not enough.<br>";
            }


            /*
             * Cek Penarikan
             */

            if ($transfer > ($balance - $minSaldo)) {
                $errorMsg .= "* Transfer amount is over than your balance.<br>";

            }


            $msg = "";
            if ($errorMsg == "") {

                $conn->beginTransaction();

                // Insert Withdraw
                $transStorage = new \MLM\Model\Transaction\Storage($db);
                $dataW = $transStorage->transferwallet($identity->member_id, $transType, $transfer, $fromAccount, $toAccount);
                while($dataW->next()){
                        $res = $dataW->current();
                        $msg = $res["out_msg"];
                        $code = $res['out_code'];
                }

                if ($code == '0') {
                    $conn->commit();
                    return $this->redirect()->toUrl('transferwallet?msg='.$msg);

                } else {
                    $conn->rollback();
                    $view->setVariable('errmsg', $msg);
                }
            }else{

                $view->setVariable('errmsg', $errorMsg);                
            }


            //$this->view->id = $msg;
        } else {

            $account = $identity->member_code;

            $getBalance = $transAccStorage->getTotalBalance($account);
            while($getBalance->next()){
                    $balance = $getBalance->current();
                    $view->setVariable('amount', $balance["amount"]);
                    $view->setVariable('amount2', $balance["amount2"]);
            }


            $view->setVariable('acc_num', $account);

            //Get Minimal Balance
            $configStorage = new \MLM\Model\Sysconfig\Storage($db);
            $getMinBalance = $configStorage->getConfigByName('MIN_BALANCE');
            while($getMinBalance->next()){
                    $minBalance = $getMinBalance->current();
                    $view->setVariable('minbalance', $minBalance['int_value']);
            }

            //Get Minimal Transfer
            $getMinBalance = $configStorage->getConfigByName('MIN_TRANSFER');
            while($getMinBalance->next()){
                    $minBalance = $getMinBalance->current();
                    $view->setVariable('mintransfer', $minBalance['int_value']);
            }


        }

        $script = $this->getServiceLocator()->get('viewhelpermanager')
                ->get('inlineScript');
        $script->appendScript("
          jQuery(function($) {
            
            $('.chosen-select').chosen();

            $('#modal-form').on('shown.bs.modal', function() {
                $(this).find('.chosen-container').each(function() {
                    $(this).find('a:first-child').css('width', '210px');
                    $(this).find('.chosen-drop').css('width', '210px');
                    $(this).find('.chosen-search input').css('width', '200px');
                });
            });

            $('[data-rel=popover]').popover({html:true});
        })
        ");
        
        $getParams = $this->getRequest()->getQuery();
        $view->setVariable('msg', $getParams["msg"]);
        $view->setVariable('data', $data);
        
        //Get Messages Notif
        $this->getMsgNotif($identity->member_type_id, $identity->member_id);
        $this->layout()->navMenu = "<li class='active'>Transfer</li> <li class='active'>Transfer Between Wallet </li>";

        return $view;
    }


    public function transferewalletAction() {

        $identity = $this->hasSession();

        $this->layout('layout/member');
        $view = new ViewModel();
        // init data and instance object

        $request = $this->getRequest();

        $db = $this->_db;
        $conn = $db->getDriver()->getConnection();
        $transAccStorage = new \MLM\Model\Member\Account\Storage($db);

        if ($request->isPost()) {

            $formData = $request->getPost();

            $fromAccount = $formData['acc_num'];
            $transfer = $formData['transfer'];
            $toAccount = $formData['to_account'];
            $minSaldo = $formData["minbalance"];
            

            $data = get_object_vars($formData);

            $errorMsg = "";

            //Pastikan Balance
            //$modelRek = new Application_Model_Rekening();


            $getBalance = $transAccStorage->getTotalBalance($fromAccount);

            $balance = 0;
            while($getBalance->next()){
                $res = $getBalance->current();
                $balance = $res["amount"];
            }

            //cek minimum saldo
            if ($minSaldo > $balance || $minSaldo > ($balance - $transfer)) {
                $errorMsg .= "* Your Balance is not enough.<br>";
            }


            /*
             * Cek Penarikan
             */

            if ($transfer > ($balance - $minSaldo)) {
                $errorMsg .= "* Transfer amount is over than your balance.<br>";

            }


            /*
             * Cek Akun Tujuan
             */
            $toAcc = $transAccStorage->getAccountDetailByAcc($toAccount);
            $x = 0;
            while($toAcc->next()){
                    $res = $toAcc->current();
                    $x++;
            }
            if ($x == 0) {
                $errorMsg .= "* Destination Account is not registered.<br>";

            }

            $msg = "";
            if ($errorMsg == "") {

                $conn->beginTransaction();

                // Insert Withdraw
                $transStorage = new \MLM\Model\Transaction\Storage($db);
                $dataW = $transStorage->transferwallet($identity->member_id, "T012", $transfer, $fromAccount, $toAccount);
                while($dataW->next()){
                        $res = $dataW->current();
                        $msg = $res["out_msg"];
                        $code = $res['out_code'];
                }

                if ($code == '0') {
                    $conn->commit();
                    return $this->redirect()->toUrl('transferewallet?msg='.$msg);

                } else {
                    $conn->rollback();
                    $view->setVariable('errmsg', $msg);
                }
            }else{

                $view->setVariable('errmsg', $errorMsg);
                $view->setVariable('data', $data);
            }


            //$this->view->id = $msg;
        } else {

            $account = $identity->member_code;

            $getBalance = $transAccStorage->getTotalBalance($account);
            while($getBalance->next()){
                    $balance = $getBalance->current();
                    $view->setVariable('balance', $balance["amount"]);
                    $view->setVariable('balance2', $balance["amount2"]);
            }


            $view->setVariable('acc_num', $account);

            //Get Minimal Balance
            $configStorage = new \MLM\Model\Sysconfig\Storage($db);
            $getMinBalance = $configStorage->getConfigByName('MIN_BALANCE');
            while($getMinBalance->next()){
                    $minBalance = $getMinBalance->current();
                    $view->setVariable('minbalance', $minBalance['int_value']);
            }

            //Get Minimal Transfer
            $getMinBalance = $configStorage->getConfigByName('MIN_TRANSFER');
            while($getMinBalance->next()){
                    $minBalance = $getMinBalance->current();
                    $view->setVariable('mintransfer', $minBalance['int_value']);
            }


        }

        $getParams = $this->getRequest()->getQuery();
        $view->setVariable('msg', $getParams["msg"]);

        //Get Messages Notif
        $this->getMsgNotif($identity->member_type_id, $identity->member_id);
        $this->layout()->navMenu = "<li class='active'>Transfer</li> <li class='active'>Transfer E-Wallet to E-Wallet </li>";

        return $view;
    }


    public function withdrawwireAction() {

        $identity = $this->hasSession();

        $this->layout('layout/member');
        $view = new ViewModel();
        // init data and instance object

        $request = $this->getRequest();

        $db = $this->_db;
        $conn = $db->getDriver()->getConnection();
        $transAccStorage = new \MLM\Model\Member\Account\Storage($db);

        if ($request->isPost()) {

            $formData = $request->getPost();
            $minWD = $formData["minwithdraw"];
            $minSaldo = $formData["minbalance"];
            $through = $formData['through'];
            $biaya = 0;

            if ($through == 1){     // Bank Wire

                $wallet = $formData['wallet'];
                $amount = $formData['amount'];
                $toAccount = $formData['acc_num'];
                $toAccName = $formData['acc_name'];
                $accType = $formData['acc_type'];
                $bankName = $formData['bank_name'];
                $swiftCode = $formData['swift_code'];
                $address = $formData['address'];
                $bankAddr = $formData['bank_addr'];
                $info = $formData['info'];


            }else{     // Perfect Money or Ego Pay

                $wallet = $formData['wallet2'];
                $amount = $formData['amount2'];
                $toAccount = $formData['acc_num2'];
                $toAccName = $formData['acc_name2'];

                $accType = 0;
                $bankName = "";
                $swiftCode = "";
                $address = "";
                $bankAddr = "";
                $info = "";

            }



            $data = get_object_vars($formData);

            $errorMsg = "";

            //Pastikan Balance
            //$modelRek = new Application_Model_Rekening();


            $getBalance = $transAccStorage->getTotalBalance($identity->member_code);

            $balance = 0;
            while($getBalance->next()){
                $res = $getBalance->current();
                $balanceEWallet = $res["amount"];
                $balanceRoiWallet = $res["amount_1"];
                $balanceRefWallet = $res["amount_2"];
                $balanceBinWallet = $res["amount_3"];
                $balanceShopWallet = $res["amount_4"];

                if ($wallet == 0) $balance = $balanceEWallet;
                if ($wallet == 1) $balance = $balanceRoiWallet;
                if ($wallet == 2) $balance = $balanceRefWallet;
                if ($wallet == 3) $balance = $balanceBinWallet;
                if ($wallet == 4) $balance = $balanceShopWallet;
            }

            //cek minimum saldo
            if ($minSaldo > $balance || $minSaldo > ($balance - ($amount + $biaya))) {
                $errorMsg .= "* Your Balance is not enough.<br>";
            }


            /*
             * Cek Penarikan
             */

            if ($amount > $balance) {
                $errorMsg .= "* Withdraw amount is over than your balance.<br>";

            }



            $msg = "";
            if ($errorMsg == "") {

                $conn->beginTransaction();

                // Insert Withdraw
                $transStorage = new \MLM\Model\Transaction\Storage($db);
                $dataW = $transStorage->withdrawWallet($identity->member_id, $identity->member_code, $through, $wallet, $amount, $toAccount, $toAccName, $accType, $bankName, $swiftCode, $address, $bankAddr, $info);
                while($dataW->next()){
                        $res = $dataW->current();
                        $msg = $res["out_msg"];
                        $code = $res['out_code'];
                }

                if ($code == '0') {
                    $conn->commit();
                    return $this->redirect()->toUrl('withdrawwire?msg='.$msg);

                } else {
                    $conn->rollback();
                    $view->setVariable('errmsg', $msg);
                }
            }else{

                $view->setVariable('errmsg', $errorMsg);
            }


            //$this->view->id = $msg;
        } else {

            $account = $identity->member_code;

            $getBalance = $transAccStorage->getTotalBalance($account);
            while($getBalance->next()){
                    $balance = $getBalance->current();
                    $view->setVariable('amount', $balance["amount"]);
                    $view->setVariable('amount2', $balance["amount2"]);
            }

            $getBank = $transAccStorage->getMemberAccountBank($identity->member_id);
            while($getBank->next()){
                    $bank = $getBank->current();
                    $view->setVariable('bank', $bank['bank_acc_num']);
            }

            $view->setVariable('acc_num', $account);


            //Get withdrawal Fee
            $configStorage = new \MLM\Model\Sysconfig\Storage($db);
            $getFee = $configStorage->getConfigByName('CHARGE_WITHDRAW');
            while($getFee->next()){
                    $fee = $getFee->current();
                    $view->setVariable('biaya', $fee['int_value']);
            }

            //Get Minimal Balance
            $configStorage = new \MLM\Model\Sysconfig\Storage($db);
            $getMinBalance = $configStorage->getConfigByName('MIN_BALANCE');
            while($getMinBalance->next()){
                    $minBalance = $getMinBalance->current();
                    $view->setVariable('minbalance', $minBalance['int_value']);
            }


            //Get Minimal WIthdraw
            $getMinWithdraw = $configStorage->getConfigByName('MIN_WITHDRAW');
            while($getMinWithdraw->next()){
                    $minWithdraw = $getMinWithdraw->current();
                    $view->setVariable('minwithdraw', $minWithdraw['int_value']);
            }

        }

        $script = $this->getServiceLocator()->get('viewhelpermanager')
                ->get('inlineScript');
        $script->appendScript("
          jQuery(function($) {

            $('.chosen-select').chosen();

            $('#modal-form').on('shown.bs.modal', function() {
                $(this).find('.chosen-container').each(function() {
                    $(this).find('a:first-child').css('width', '210px');
                    $(this).find('.chosen-drop').css('width', '210px');
                    $(this).find('.chosen-search input').css('width', '200px');
                });
            });


        })
        ");

        $script->appendScript('
          jQuery(function($) {

            $("textarea[class*=autosize]").autosize({append: "\n"});
        })
        ');

        $getParams = $this->getRequest()->getQuery();
        $view->setVariable('msg', $getParams["msg"]);

        //Get Messages Notif
        $this->getMsgNotif($identity->member_type_id, $identity->member_id);
        $this->layout()->navMenu = "<li class='active'>Withdraw</li> <li class='active'>Withdraw Through Bank Wire, Perfect Money or Ego Pay </li>";

        return $view;
    }

    public function uploadpaymentAction() {

        // seting layout
        $this->layout('layout/member');
        $view = new ViewModel();
        // init data and instance object

        $identity = $this->hasSession();
        
        $memberId = $identity->member_code;

        $script = $this->getServiceLocator()->get('viewhelpermanager')
                ->get('inlineScript');
        $script->appendScript("
                          $('#id-input-file-1 , #id-input-file-2').ace_file_input({
                            no_file:'No File ...',
                            btn_choose:'Choose',
                            btn_change:'Change',
                            droppable:false,
                            onchange:null,
                            thumbnail:false //| true | large
                            //whitelist:'gif|png|jpg|jpeg'
                            //blacklist:'exe|php'
                            //onchange:''
                            //
                    });

                    $('#id-input-file-3').ace_file_input({
                            style:'well',
                            btn_choose:'Drop files here or click to choose',
                            btn_change:null,
                            no_icon:'icon-cloud-upload',
                            droppable:true,
                            thumbnail:'small'//large | fit
                            //,icon_remove:null//set null, to hide remove/reset button
                            /**,before_change:function(files, dropped) {
                                    //Check an example below
                                    //or examples/file-upload.html
                                    return true;
                            }*/
                            /**,before_remove : function() {
                                    return true;
                            }*/
                            ,
                            preview_error : function(filename, error_code) {
                                    //name of the file that failed
                                    //error_code values
                                    //1 = 'FILE_LOAD_FAILED',
                                    //2 = 'IMAGE_LOAD_FAILED',
                                    //3 = 'THUMBNAIL_FAILED'
                                    //alert(error_code);
                            }

                    }).on('change', function(){
                            //console.log($(this).data('ace_input_files'));
                            //console.log($(this).data('ace_input_method'));
                    });


                    //dynamically change allowed formats by changing before_change callback function
                    $('#id-file-format').removeAttr('checked').on('change', function() {
                            var before_change
                            var btn_choose
                            var no_icon
                            if(this.checked) {
                                    btn_choose = 'Drop images here or click to choose';
                                    no_icon = 'icon-picture';
                                    before_change = function(files, dropped) {
                                            var allowed_files = [];
                                            for(var i = 0 ; i < files.length; i++) {
                                                    var file = files[i];
                                                    if(typeof file === 'string') {
                                                            //IE8 and browsers that don't support File Object
                                                            if(! (/\.(jpe?g|png|gif|bmp)$/i).test(file) ) return false;
                                                    }
                                                    else {
                                                            var type = $.trim(file.type);
                                                            if( ( type.length > 0 && ! (/^image\/(jpe?g|png|gif|bmp)$/i).test(type) )
                                                                            || ( type.length == 0 && ! (/\.(jpe?g|png|gif|bmp)$/i).test(file.name) )//for android's default browser which gives an empty string for file.type
                                                                    ) continue;//not an image so don't keep this file
                                                    }

                                                    allowed_files.push(file);
                                            }
                                            if(allowed_files.length == 0) return false;

                                            return allowed_files;
                                    }
                            }
                            else {
                                    btn_choose = 'Drop files here or click to choose';
                                    no_icon = 'icon-cloud-upload';
                                    before_change = function(files, dropped) {
                                            return files;
                                    }
                            }
                            var file_input = $('#id-input-file-3');
                            file_input.ace_file_input('update_settings', {'before_change':before_change, 'btn_choose': btn_choose, 'no_icon':no_icon})
                            file_input.ace_file_input('reset_input');
                    });

                    /////////
                    $('#modal-form input[type=file]').ace_file_input({
                            style:'well',
                            btn_choose:'Drop files here or click to choose',
                            btn_change:null,
                            no_icon:'icon-cloud-upload',
                            droppable:true,
                            thumbnail:'large'
                    })
        ");

        $request = $this->getRequest();
        if ($request->isPost()) {
             $formData = $request->getPost();
             
             $files =  $request->getFiles()->toArray();

             $httpadapter = new \Zend\File\Transfer\Adapter\Http();
             $filesize  = new \Zend\Validator\File\Size(array('min' => 1000 )); //1KB
             $extension = new \Zend\Validator\File\Extension(array('extension' => array('jpg','jpg','jpeg','gif','png')));
             $httpadapter->setValidators(array($filesize, $extension), $files['file2']['name']);
             if($httpadapter->isValid()) {
                  
                 //$httpadapter->setDestination('/var/www/qowwam.com/web-mlm-engine/public/img/profile');
                 $httpadapter->setDestination('/var/www/fx-tradepoint.co.uk/web-member/public/img/paymentproofs');
                 //$adapter->setDestination(dirname(__DIR__).'/assets');
                 if($httpadapter->receive($files['file2']['name'])) {
                    $newfile = $httpadapter->getFileName();

                    $fileName = $files['file2']['name'];

                    $db = $this->_db;
                    $conn = $db->getDriver()->getConnection();
                    $storage = new \MLM\Model\Transaction\Storage($db);

                    $conn->beginTransaction();

                    $dataTrans = array("member_code" => $memberId,
                                        "file_name" => $fileName,
                                        "status"    => "APPROVAL",
                                        "upload_dtm" => $storage->now());

                    $save = $storage->insertDataTrans("payment_proof", $dataTrans);

                    if(!$save){
                        $conn->rollback();
                        $view->setVariable('errmsg', 'Upload Failed, please try again');
                        return $view;
                    }

                    $conn->commit();

                 }

             }else{

                $dataError = $httpadapter->getMessages();
                $error = "";
                foreach($dataError as $key=>$row)
                {
                    $error .= $row."<br>";
                }

                $view->setVariable('errmsg', 'Upload Failed: '. $error);
                return $view;

             }

            return $this->redirect()->toUrl('uploadpayment?msg=Upload Payment Proofs Success');

        }
        $getParams = $this->getRequest()->getQuery();
        $msg = $getParams["msg"];
        $view->setVariable('msg', $msg);
        //Get Messages Notif
        $this->getMsgNotif($identity->member_type_id, $identity->member_id);
        $this->layout()->navMenu = "<li class='active'>Upload Payment Proofs </li>";

        return $view;
    }
    
    //Get Messages Notif
    private function getMsgNotif($memberTypeId, $memberId){


        if ($memberId == 100) $memberId2 = $memberId;
        else{
            $identity = $this->hasSession();
            //$memberId2 = ($identity->member_reff_id == "") ? $memberId : $identity->member_reff_id;
            $memberId2 = $memberId;
            $isAgent = $identity->member_reff_id;
        }


        $notifStorage = new \MLM\Model\Notification\Storage($this->_db);
        $notifMsg = new \MLM\Model\Notification($notifStorage);
        $newMsgCnt = $notifMsg->getCountNewMsg($memberId);
        $newMsgList = $notifMsg->getNewMsgList($memberId);
        $newAlertCnt = $notifMsg->getCountAlertApproval($memberTypeId, $memberId2, $isAgent);
        $newAlertList = $notifMsg->getAlertApproval($memberTypeId, $memberId2, $isAgent);

        $action = $this->getEvent()->getRouteMatch()->getParam('action');
        $control = $this->getEvent()->getRouteMatch()->getParam('controller');

        $this->layout()->menu = $control.'\\'.$action;
        $this->layout()->newMsgCnt = $newMsgCnt;
        $this->layout()->newMsgList = $newMsgList;
        $this->layout()->newAlertCnt = $newAlertCnt;
        $this->layout()->newAlertList = $newAlertList;

    }

    
    private function hasSession() {
        $auth = new AuthenticationService();

        //$identity = $auth->getIdentity();

        if (!$auth->hasIdentity()) {
            return $this->redirect()->toRoute('application/default', array('controller' => 'Index', 'action' => 'login'));
        } else {
            return $auth->getIdentity();
        }
    }

}
